<template>
  <el-row :gutter="40">
    <el-col v-for="item in recombItems" :span="props.span">
      <MerakControl
        v-bind="item"
        v-model="modelValue[item.field]"
        :ref="el => (recombRefs[item.field] = el as MerakControlInstance)"
        :default-selected-label="modelValue[`${item.field}_txt`]"
        :query-options="recombQueryOptions"
        @change="recombChange"
      >
        <template v-for="prefix in Object.keys(recombPrefix)" #[prefix]> {{ recombPrefix[prefix] }}_ </template>
        <template #num_in_packing>
          <el-input class="qf_input" v-model="modelValue[item.field]" v-num="{ min: 1 }" />
        </template>
      </MerakControl>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { reactive } from "vue";

import useProductForm from "@/hooks/useProductForm";

import { ElRow, ElCol, ElInput } from "element-plus";

import MerakControl, { MerakControlInstance, MerakControlProps, MerakControlOption } from "@/components/MerakControl";

const props = defineProps<{
  id: string | number;
  span: number;
  items: MerakControlProps[];
  editor: boolean;
  suite: 0 | 1;
}>();

const emits = defineEmits<{
  renderColor: [colors: MerakControlOption[]];
  renderSpu: [spu: string];
  renderSizeStandard: [size: string | number];
  changeRequired: [requires: Record<string, boolean>];
}>();

const modelValue = defineModel<Record<string, any>>({ default: {} });

const requiredKeys = reactive<Array<string>>([]);

const linkage = (field: string, value: any) => {
  const linkageMap: Record<string, () => void> = {
    color: () => {
      emits("renderColor", value);
    },
    spu: () => {
      emits("renderSpu", value);
    },
    sku: () => {
      emits("renderSpu", value);
    },
    size: () => {
      emits("renderSizeStandard", value);
    },
    gender: () => {
      emits("changeRequired", {
        cc_head_circum: [209, 211].includes(value)
      });
    }
  };
  linkageMap[field]?.();
};

const { recombRefs, recombPrefix, recombItems, recombQueryOptions, recombChange, recombReduction } = useProductForm({
  typeId: () => props.id,
  suite: () => props.suite,
  formItems: () => props.items,
  formData: modelValue,
  editor: () => true,
  requiredKeys,
  linkage
});

defineExpose({
  recombReduction,
  setRequired: (requires: Record<string, boolean>) => {
    Object.entries(requires).forEach(([key, result]) => {
      const index = requiredKeys?.findIndex(requiredKey => requiredKey === key);
      if (result && index === -1) {
        requiredKeys.push(key);
      } else if (!result && index !== -1) {
        requiredKeys.splice(index, 1);
      }
    });
  },
  closePanel: () => {
    Object.values(recombRefs).forEach(ref => ref.closePopover());
  }
});
</script>

<style scoped lang="scss"></style>
